<template>
  <div class="document-detail">
    <div v-if="!document" class="no-document">
      <div class="placeholder">
        <h3>📄 选择一个文档</h3>
        <p>从左侧树中选择一个文档来查看详情</p>
      </div>
    </div>

    <div v-else class="document-view">
      <div class="detail-header">
        <!-- 编辑模式标题 -->
        <input 
          v-if="isEditing" 
          v-model="editingDocument.name" 
          class="document-title-input" 
          type="text"
          placeholder="请输入文档标题"
        />
        <!-- 查看模式标题 -->
        <h2 v-else class="document-title">{{ document.name }}</h2>

        <div class="header-actions">
          <!-- 编辑模式按钮 -->
          <template v-if="isEditing">
            <button @click="onSave" class="action-btn save-btn" :disabled="saving" title="保存">
              {{ saving ? '💾' : '✅' }}
            </button>
            <button @click="onCancelEdit" class="action-btn cancel-btn" title="取消">
              ❌
            </button>
          </template>
          <!-- 查看模式按钮 -->
          <template v-else>
            <button @click="onEdit" class="action-btn edit-btn" title="编辑">
              ✏️
            </button>
            <button @click="toggleFavorite" class="action-btn favorite-btn" 
                    :class="{ 'favorited': isFavorited }" 
                    :title="isFavorited ? '取消收藏' : '收藏文档'"
                    :disabled="favoriteLoading">
              {{ favoriteLoading ? '⏳' : (isFavorited ? '❤️' : '🤍') }}
            </button>
            <button @click="showCreateItemDialog" class="action-btn add-item-btn" title="添加子项">
              ➕
            </button>
            <button @click="onDelete" class="action-btn delete-btn" title="删除">
              🗑️
            </button>
          </template>
        </div>
      </div>

      <!-- 编辑模式内容区域 -->
      <div v-if="isEditing" class="document-content editing">
        <div class="edit-form">
          <div class="form-group">
            <label for="namespaceSelect">文档空间：</label>
            <el-select
              v-model="editingDocument.namespaceId"
              placeholder="请选择文档空间"
              :loading="loadingSpaces"
              loading-text="加载空间列表中..."
              style="width: 100%"
              size="large"
            >
              <el-option
                v-for="space in spaces"
                :key="space.id"
                :label="space.name"
                :value="space.id"
              >
                <div class="space-option">
                  <div class="space-info">
                    <span class="space-name">{{ space.name }}</span>
                    <span class="space-desc" v-if="space.description">{{ space.description }}</span>
                  </div>
                  <div class="space-color" v-if="space.color" :style="{ backgroundColor: space.color }"></div>
                </div>
              </el-option>
            </el-select>
          </div>
          <div class="form-group">
            <label for="contentEditor">文档内容：</label>
            
            <!-- 编辑工具栏 -->
            <div class="editor-toolbar">
              <ImageUploader 
                @success="handleImageUploadSuccess"
                @error="handleImageUploadError"
                :multiple="true"
                :maxSize="5"
              />
              <div class="toolbar-tip">
                💡 支持拖拽图片到编辑器或使用Ctrl+V粘贴图片
              </div>
            </div>
            
            <textarea 
              ref="contentEditor"
              id="contentEditor"
              v-model="editingDocument.content" 
              class="content-editor"
              placeholder="请输入文档内容（支持Markdown语法）&#10;&#10;图片上传：&#10;• 点击上方【添加图片】按钮&#10;• 拖拽图片到此区域&#10;• 使用Ctrl+V粘贴剪贴板中的图片"
              rows="20"
              @paste="handlePaste"
              @dragover.prevent="handleDragOver"
              @drop.prevent="handleDrop"
              @dragleave="handleDragLeave"
            ></textarea>
          </div>
        </div>
      </div>
      
      <!-- 查看模式内容区域 -->
      <div v-else-if="document.content && document.content.trim()" class="document-content">
        <div class="content-body">
          <MarkdownRenderer
              v-if="viewMode === 'markdown'"
              :content="document.content"
          />
          <pre v-else class="raw-content">{{ document.content }}</pre>
        </div>
      </div>

      <!-- 文档子项列表 -->
      <div class="items-section">
        <div v-if="documentItems.length > 0" class="items-list">
          <div
              v-for="item in documentItems"
              :key="item.id"
              class="item-card"
          >
            <div class="item-header">
              <h4 class="item-title">{{ item.name }}</h4>
              <div class="item-actions">
                <button @click="editItem(item)" class="action-btn edit-btn" title="编辑">
                  ✏️
                </button>
                <button @click="deleteItem(item)" class="action-btn delete-btn" title="删除">
                  🗑️
                </button>
              </div>
            </div>
            <div class="item-content">
              <MarkdownRenderer :content="item.content || '暂无内容'"/>
            </div>
            <div class="item-meta">
              <span class="meta-info" v-if="item.sortNo">排序: {{ item.sortNo }}</span>
              <span class="meta-info" v-if="item.updatedTime">更新: {{ formatDate(item.updatedTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档子项创建/编辑弹窗 -->
    <div v-if="showItemDialog" class="dialog-overlay" @click="closeItemDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEditingItem ? '编辑文档子项' : '添加文档子项' }}</h3>
          <button @click="closeItemDialog" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="submitItemForm" class="dialog-form">
          <div class="form-group">
            <label for="itemName">子项名称：</label>
            <input
                id="itemName"
                v-model="itemFormData.name"
                type="text"
                placeholder="请输入子项名称"
                required
                class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="itemContent">子项内容：</label>
            <textarea
                id="itemContent"
                v-model="itemFormData.content"
                placeholder="请输入子项内容（支持Markdown）"
                class="form-input form-textarea"
                rows="8"
            ></textarea>
          </div>
          <div class="form-group">
            <label for="itemSortNo">排序号：</label>
            <input
                id="itemSortNo"
                v-model.number="itemFormData.sortNo"
                type="number"
                placeholder="可选，用于排序（默认为0）"
                class="form-input"
            />
          </div>
          <div class="dialog-actions">
            <button type="button" @click="closeItemDialog" class="cancel-btn">取消</button>
            <button type="submit" :disabled="submittingItem" class="submit-btn">
              {{ submittingItem ? '保存中...' : (isEditingItem ? '更新' : '创建') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue'
import type {Document, DocumentItem, DocumentItemRequest} from '../types/document'
import type {NameSpace} from '../types/namespace'
import MarkdownRenderer from './MarkdownRenderer.vue'
import ImageUploader from './ImageUploader.vue'
import {documentItemApi, namespaceApi, documentFavoriteApi} from '../services/api'
import {toast} from '../utils/message'
import {insertTextAtCursor, getImageFromClipboard} from '../utils/imageUtils'

interface Props {
  document: Document | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  edit: [document: Document]
  delete: [id: number]
  select: [document: Document]
  refresh: []
}>()

const viewMode = ref<'markdown' | 'text'>('markdown')

// 编辑模式状态
const isEditing = ref(false)
const editingDocument = ref({
  name: '',
  content: '',
  namespaceId: null as number | null
})
const saving = ref(false)

// 空间相关状态
const spaces = ref<NameSpace[]>([])
const loadingSpaces = ref(false)

// 文档子项相关状态
const documentItems = ref<DocumentItem[]>([])
const loadingItems = ref(false)

// 子项弹窗相关状态
const showItemDialog = ref(false)
const isEditingItem = ref(false)
const editingItemId = ref<number | null>(null)
const submittingItem = ref(false)
const itemFormData = ref<DocumentItemRequest>({
  documentId: 0,
  name: '',
  content: '',
  sortNo: 0
})

// 收藏相关状态
const isFavorited = ref(false)
const favoriteLoading = ref(false)

// 编辑器相关引用
const contentEditor = ref<HTMLTextAreaElement>()

const formatDate = (dateString: string): string => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN')
  } catch {
    return dateString
  }
}

// 进入编辑模式
const onEdit = async () => {
  if (props.document) {
    isEditing.value = true
    editingDocument.value = {
      name: props.document.name,
      content: props.document.content || '',
      namespaceId: props.document.namespaceId || null
    }
    
    // 加载空间列表
    await loadSpaces()
  }
}

// 取消编辑
const onCancelEdit = () => {
  isEditing.value = false
  editingDocument.value = {
    name: '',
    content: '',
    namespaceId: null
  }
}

// 加载空间列表
const loadSpaces = async () => {
  try {
    loadingSpaces.value = true
    spaces.value = await namespaceApi.getAll()
  } catch (error) {
    console.error('加载空间列表失败:', error)
    toast.error('加载空间列表失败')
  } finally {
    loadingSpaces.value = false
  }
}

// 保存文档
const onSave = async () => {
  if (!props.document) return
  
  saving.value = true
  try {
    // 发送保存事件给父组件
    emit('edit', {
      ...props.document,
      name: editingDocument.value.name,
      content: editingDocument.value.content,
      namespaceId: editingDocument.value.namespaceId ?? props.document.namespaceId
    })
    
    isEditing.value = false
    toast.success('文档保存成功')
  } catch (error: any) {
    console.error('保存文档失败:', error)
    toast.error('保存文档失败')
  } finally {
    saving.value = false
  }
}

const onDelete = async () => {
  if (!props.document) return

  const confirmed = await toast.confirm(
      '确定要删除这个文档吗？此操作不可撤销。',
      {
        title: '删除文档',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
  )

  if (confirmed) {
    emit('delete', props.document.id)
  }
}


// 加载文档子项
const loadDocumentItems = async (documentId: number) => {
  if (!documentId) {
    documentItems.value = []
    return
  }

  try {
    loadingItems.value = true
    documentItems.value = await documentItemApi.getByDocumentId(documentId)
  } catch (error: any) {
    console.error('加载文档子项失败:', error)
    documentItems.value = []
    // 不显示错误提示，因为可能是网络问题或后端未启动
  } finally {
    loadingItems.value = false
  }
}

// 显示创建子项弹窗
const showCreateItemDialog = () => {
  if (!props.document) {
    toast.warning('请先选择一个文档')
    return
  }

  isEditingItem.value = false
  editingItemId.value = null
  itemFormData.value = {
    documentId: props.document.id,
    name: '',
    content: '',
    sortNo: documentItems.value.length + 1
  }
  showItemDialog.value = true
}

// 编辑子项
const editItem = (item: DocumentItem) => {
  isEditingItem.value = true
  editingItemId.value = item.id || null
  itemFormData.value = {
    documentId: item.documentId,
    name: item.name,
    content: item.content,
    sortNo: item.sortNo || 0
  }
  showItemDialog.value = true
}

// 删除子项
const deleteItem = async (item: DocumentItem) => {
  if (!item.id) return

  const confirmed = await toast.confirm(
      `确定要删除子项"${item.name}"吗？此操作不可撤销。`,
      {
        title: '删除子项',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
  )

  if (!confirmed) return

  try {
    await documentItemApi.delete(item.id)
    documentItems.value = documentItems.value.filter(i => i.id !== item.id)
    toast.success('子项删除成功')
  } catch (error: any) {
    console.error('删除子项失败:', error)
    toast.error('删除子项失败')
  }
}

// 关闭子项弹窗
const closeItemDialog = () => {
  showItemDialog.value = false
  isEditingItem.value = false
  editingItemId.value = null
  itemFormData.value = {
    documentId: 0,
    name: '',
    content: '',
    sortNo: 0
  }
  submittingItem.value = false
}

// 提交子项表单
const submitItemForm = async () => {
  if (!props.document) return

  submittingItem.value = true

  try {
    if (isEditingItem.value && editingItemId.value) {
      // 更新子项
      const updatedItem = await documentItemApi.update(editingItemId.value, itemFormData.value)
      const index = documentItems.value.findIndex(item => item.id === editingItemId.value)
      if (index !== -1) {
        documentItems.value[index] = updatedItem
      }
      toast.success('子项更新成功')
    } else {
      // 创建新子项
      const newItem = await documentItemApi.create(itemFormData.value)
      documentItems.value.push(newItem)
      toast.success('子项创建成功')
    }
    closeItemDialog()
  } catch (error: any) {
    console.error('保存子项失败:', error)
    toast.error('保存子项失败')
  } finally {
    submittingItem.value = false
  }
}

// 检查文档是否已收藏
const checkFavoriteStatus = async (documentId: number) => {
  try {
    isFavorited.value = await documentFavoriteApi.isFavorited(documentId)
  } catch (error: any) {
    console.error('检查收藏状态失败:', error)
    // 不显示错误提示，可能是网络问题或后端未启动
    isFavorited.value = false
  }
}

// 切换收藏状态
const toggleFavorite = async () => {
  if (!props.document) return
  
  favoriteLoading.value = true
  try {
    if (isFavorited.value) {
      // 取消收藏
      await documentFavoriteApi.removeFavorite(props.document.id)
      isFavorited.value = false
      toast.success('取消收藏成功')
    } else {
      // 添加收藏
      await documentFavoriteApi.addFavorite({ documentId: props.document.id })
      isFavorited.value = true
      toast.success('收藏成功')
    }
  } catch (error: any) {
    console.error('切换收藏状态失败:', error)
    toast.error('操作失败，请稍后重试')
  } finally {
    favoriteLoading.value = false
  }
}

// 图片上传成功处理
const handleImageUploadSuccess = (markdown: string) => {
  const textarea = contentEditor.value
  if (textarea) {
    // 使用insertTextAtCursor在光标位置插入
    insertTextAtCursor(textarea, '\n' + markdown + '\n')
    // 更新Vue响应式数据
    editingDocument.value.content = textarea.value
  } else {
    // 如果无法获取textarea引用，直接追加到内容末尾
    editingDocument.value.content += '\n' + markdown + '\n'
  }
  
  console.log('图片上传成功，已插入markdown:', markdown)
}

// 图片上传失败处理
const handleImageUploadError = (error: string) => {
  console.error('图片上传失败:', error)
  toast.error(`图片上传失败: ${error}`)
}

// 处理粘贴事件
const handlePaste = async (event: ClipboardEvent) => {
  const image = getImageFromClipboard(event)
  if (image && contentEditor.value) {
    event.preventDefault()
    
    try {
      // 这里可以调用图片上传API
      toast.info('检测到粘贴图片，请使用上方的图片上传按钮')
    } catch (error) {
      console.error('处理粘贴图片失败:', error)
      toast.error('处理粘贴图片失败')
    }
  }
}

// 处理拖拽悬停
const handleDragOver = (_event: DragEvent) => {
  if (contentEditor.value) {
    contentEditor.value.style.borderColor = '#42b883'
    contentEditor.value.style.backgroundColor = 'rgba(66, 184, 131, 0.05)'
  }
}

// 处理拖拽离开
const handleDragLeave = (_event: DragEvent) => {
  if (contentEditor.value) {
    contentEditor.value.style.borderColor = '#42b883'
    contentEditor.value.style.backgroundColor = 'white'
  }
}

// 处理拖拽放置
const handleDrop = async (event: DragEvent) => {
  if (contentEditor.value) {
    contentEditor.value.style.borderColor = '#42b883'
    contentEditor.value.style.backgroundColor = 'white'
  }
  
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    event.preventDefault()
    const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'))
    
    if (imageFiles.length > 0) {
      toast.info(`检测到 ${imageFiles.length} 个图片文件，请使用上方的图片上传按钮`)
    }
  }
}

// 监听文档变化，加载对应的子项并退出编辑模式
watch(() => props.document?.id, (newId) => {
  // 退出编辑模式
  if (isEditing.value) {
    isEditing.value = false
    editingDocument.value = { name: '', content: '', namespaceId: null }
  }
  
  if (newId) {
    loadDocumentItems(newId)
    checkFavoriteStatus(newId) // 检查收藏状态
  } else {
    documentItems.value = []
    isFavorited.value = false
  }
}, {immediate: true})

// 初始化时从localStorage读取用户偏好
const savedViewMode = localStorage.getItem('documentViewMode') as 'markdown' | 'text'
if (savedViewMode && ['markdown', 'text'].includes(savedViewMode)) {
  viewMode.value = savedViewMode
}

// 暴露方法给父组件调用
defineExpose({
  onEdit
})
</script>

<style scoped>
.document-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.no-document {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder {
  text-align: center;
  color: #999;
}

.placeholder h3 {
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
}

.placeholder p {
  margin: 0;
  font-size: 1rem;
}

.document-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  padding: 2rem 2rem 1rem 2rem;
  border-bottom: 1px solid #e1e1e1;
  background: #f9f9f9;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  position: relative;
}

.document-title {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
  text-align: center;
}

.document-title-input {
  margin: 0;
  padding: 0.5rem;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
  text-align: center;
  border: 2px solid #42b883;
  border-radius: 6px;
  background: white;
  min-width: 300px;
}

.document-title-input:focus {
  outline: none;
  border-color: #369870;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
  position: absolute;
  right: 2rem;
}

.action-btn {
  padding: 0.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.2rem;
  height: 2.2rem;
}

.edit-btn {
  background: #74b9ff;
  color: white;
}

.edit-btn:hover {
  background: #0984e3;
}

.delete-btn {
  background: #fd79a8;
  color: white;
}

.delete-btn:hover {
  background: #e84393;
}

.add-item-btn {
  background: #00b894;
  color: white;
}

.add-item-btn:hover {
  background: #00a085;
}

.save-btn {
  background: #00b894;
  color: white;
}

.save-btn:hover:not(:disabled) {
  background: #00a085;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cancel-btn {
  background: #fd79a8;
  color: white;
}

.cancel-btn:hover {
  background: #e84393;
}

.favorite-btn {
  background: #ffeaa7;
  color: #2d3436;
}

.favorite-btn:hover {
  background: #fdcb6e;
}

.favorite-btn.favorited {
  background: #e17055;
  color: white;
}

.favorite-btn.favorited:hover {
  background: #d63031;
}

.favorite-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.document-meta {
  padding: 1rem 2rem;
  background: #f8f9fa;
  border-bottom: 1px solid #e1e1e1;
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  flex-shrink: 0;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.meta-label {
  color: #666;
  font-size: 0.9rem;
  font-weight: 500;
}

.meta-value {
  color: #2c3e50;
  font-size: 0.9rem;
}

.document-content {
  flex: 1;
  overflow-y: auto;
}

.document-content.editing {
  padding: 2rem;
}

.edit-form {
  max-width: 800px;
  margin: 0 auto;
}

.edit-form .form-group {
  margin-bottom: 1.5rem;
}

.edit-form label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 600;
  font-size: 0.95rem;
}

.edit-form .form-select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #42b883;
  border-radius: 6px;
  font-size: 1rem;
  background: white;
}

.edit-form .form-select:focus {
  outline: none;
  border-color: #369870;
}

.edit-form .form-select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 空间选项样式 */
.space-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0.25rem 0;
}

.space-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.space-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
}

.space-desc {
  font-size: 0.75rem;
  color: #666;
  margin-top: 0.125rem;
}

.space-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.space-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.space-count {
  font-size: 0.75rem;
  color: #999;
  background: #f0f0f0;
  padding: 0.125rem 0.375rem;
  border-radius: 8px;
  font-weight: 500;
}

.content-editor {
  width: 100%;
  border: 2px solid #42b883;
  border-radius: 6px;
  padding: 1.5rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  resize: vertical;
  min-height: 400px;
}

.content-editor:focus {
  outline: none;
  border-color: #369870;
}

.content-editor.drag-over {
  border-color: #42b883;
  background-color: rgba(66, 184, 131, 0.05);
}

/* 编辑器工具栏样式 */
.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  padding: 0.5rem 0;
}

.toolbar-tip {
  font-size: 0.8rem;
  color: #666;
  font-style: italic;
}


.content-body {
  background: #f8f9fa;
  border: 1px solid #e1e1e1;
  padding: 1.5rem;
  min-height: 200px;
}

.raw-content {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 1rem;
  line-height: 1.6;
  color: #2c3e50;
}


.document-actions {
  padding: 1rem 2rem 2rem 2rem;
  border-top: 1px solid #e1e1e1;
  background: #f9f9f9;
  display: flex;
  gap: 1rem;
  flex-shrink: 0;
}

.primary-btn, .secondary-btn {
  padding: 0.7rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.primary-btn {
  background: #42b883;
  color: white;
}

.primary-btn:hover {
  background: #369870;
}

.secondary-btn {
  background: white;
  color: #666;
  border: 1px solid #e1e1e1;
}

.secondary-btn:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #42b883;
  color: #42b883;
}

.secondary-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .detail-header {
    padding: 1rem;
    flex-direction: column;
    gap: 1rem;
    align-items: center;
    justify-content: center;
  }

  .document-title {
    font-size: 1.2rem;
  }
  
  .document-title-input {
    font-size: 1.2rem;
    min-width: 250px;
  }
  
  .content-editor {
    min-height: 300px;
    font-size: 0.9rem;
  }

  .header-actions {
    position: static;
    right: auto;
  }

  .document-content {
    padding: 1rem 0;
  }

  .document-meta {
    padding: 1rem;
    flex-direction: column;
    gap: 0.5rem;
  }


  .document-actions {
    padding: 1rem;
    flex-direction: column;
  }
}

/* 文档子项样式 */
.items-section {
  padding: 0 2rem 2rem 2rem;
  flex-shrink: 0;
}

.items-header {
  margin-bottom: 1rem;
}

.items-header h3 {
  margin: 0;
  color: #42b883;
  font-size: 1.2rem;
}


.no-items {
  text-align: center;
  padding: 3rem 0;
  color: #999;
}

.no-items p {
  margin: 0 0 1rem 0;
  font-size: 1rem;
}

.items-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
}

.item-card {
  background: white;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  padding: 1.5rem;
  transition: all 0.2s;
}

.item-card:hover {
  border-color: #42b883;
  box-shadow: 0 2px 8px rgba(66, 184, 131, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.item-title {
  margin: 0;
  color: #2c3e50;
  font-size: 1.1rem;
  font-weight: 600;
  flex: 1;
}

.item-actions {
  display: flex;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.2s;
}

.item-card:hover .item-actions {
  opacity: 1;
}

.item-content {
  margin-bottom: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #42b883;
}

.item-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.8rem;
  color: #666;
  border-top: 1px solid #f0f0f0;
  padding-top: 1rem;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

/* 深色主题下的子项样式 */
.dark .item-card {
  background: #2d2d2d;
  border-color: #3d3d3d;
}

.dark .item-card:hover {
  border-color: #42b883;
  box-shadow: 0 2px 8px rgba(66, 184, 131, 0.2);
}

.dark .item-title {
  color: #e6e6e6;
}

.dark .item-content {
  background: #1a1a1a;
  border-left-color: #42b883;
}

.dark .item-meta {
  color: #b3b3b3;
  border-top-color: #3d3d3d;
}

.dark .no-items {
  color: #b3b3b3;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #999;
  padding: 0.25rem;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  color: #666;
  background: #f5f5f5;
}

.dialog-form {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #e1e1e1;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #42b883;
}

.form-textarea {
  min-height: 120px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.cancel-btn, .submit-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f8f8;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.submit-btn {
  background: #42b883;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #369870;
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 深色主题下的弹窗样式 */
.dark .dialog {
  background: #2d2d2d;
  color: #e6e6e6;
}

.dark .dialog-header {
  border-bottom-color: #3d3d3d;
}

.dark .dialog-header h3 {
  color: #e6e6e6;
}

.dark .close-btn {
  color: #b3b3b3;
}

.dark .close-btn:hover {
  color: #e6e6e6;
  background: #3d3d3d;
}

.dark .form-group label {
  color: #e6e6e6;
}

.dark .form-input {
  background: #1a1a1a;
  border-color: #3d3d3d;
  color: #e6e6e6;
}

.dark .form-input:focus {
  border-color: #42b883;
}

.dark .form-input::placeholder {
  color: #808080;
}

.dark .cancel-btn {
  background: #3d3d3d;
  color: #b3b3b3;
}

.dark .cancel-btn:hover {
  background: #4a4a4a;
}

/* 平板端适配 */
@media (max-width: 1024px) and (min-width: 769px) {
  .items-list {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .items-section {
    padding: 0 1rem 1rem 1rem;
  }


  .items-list {
    grid-template-columns: 1fr;
    gap: 0.8rem;
  }

  .item-card {
    padding: 1rem;
  }

  .item-header {
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }

  .item-actions {
    opacity: 1;
  }

  .item-meta {
    flex-direction: column;
    gap: 0.5rem;
  }

  .dialog {
    width: 95%;
    margin: 1rem;
  }

  .dialog-header {
    padding: 1rem;
  }

  .dialog-form {
    padding: 1rem;
  }
}
</style>